package com.tedu.excelinportdamo.controller;


import com.tedu.excelinportdamo.common.result.JsonResult;
import com.tedu.excelinportdamo.common.result.StatusCode;
import com.tedu.excelinportdamo.pojo.dto.NodeDTO;
import com.tedu.excelinportdamo.service.NodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("/api/node")
@Api(tags = "01.Excel 文件导入和查看DEMO")
@Slf4j
public class NodeController {

    @Autowired
    private NodeService nodeService;
    // 通过接口获取Excel文件 将该文件的路径传入Server 进行文件读取
    @PostMapping("/import")
    @ApiOperation(value = "导入Excel文件")
    @ApiImplicitParam(name = "file", value = "Excel文件", required = true)
    public JsonResult importExcel(@RequestParam("file") MultipartFile file) {
        log.info("文件上传开始检查");
        if (file == null || file.isEmpty()) {
            log.debug("文件为空");
            return new JsonResult(StatusCode.FILE_IS_NULL);
        }
        if (!file.getOriginalFilename().toLowerCase().endsWith(".xlsx")){
            return new JsonResult(StatusCode.FILE_NOT_EXCEL);
        }
        log.info("文件上传检查通过");
        try (InputStream in=file.getInputStream()){
            log.info("开始导入Excel文件");
            nodeService.importExcelData(in);
            return JsonResult.success();
        }catch (Exception e){
            return new JsonResult(StatusCode.FILE_CANNOT_IMPORT);
        }

    }


    @PostMapping("/search")
    @ApiOperation(value = "查询设备信息")
    public JsonResult serchNode(@RequestBody @Validated NodeDTO nodeDTO){
        log.info("查询设备信息");
        return JsonResult.success(nodeService.selectNodeList(nodeDTO));
    }



    @PostMapping("/test")
    public JsonResult handleFileUpload(@RequestParam("file") MultipartFile file) {
        /*if (file.isEmpty()||file==null) {
            return "没有文件被上传";
        } else {
            // 处理文件...
            return "文件已上传: " + file.getOriginalFilename();
        }*/
        return JsonResult.success();
    }
}
